#include "sqlite.hpp"
#include <assert.h>
using namespace std;

int select_callback(void *args, int col_count, char **result, char **field_name) // 每一行查询结果都会调用该回调，col_count表示该行列数
{
    vector<vector<string>> *ret = (vector<vector<string>> *)args; // 强转，获取容器，将查询结果放入容器
    vector<string> row;                                           // 保存一行的结果
    for (int i = 0; i < col_count; i++)
    {
        row.push_back(result[i]); // 将所有列都拼在一起
    }
    ret->push_back(row); // 将一行放入总容器
    return 0;            // 不返回0表示错误，直接终止进程
}

int main()
{
    // 1.创建/打开文件：一库一文件
    SqliteHelper helper("./stu.db");
    assert(helper.open());
    // 2.创建表(若不存在):学生表(学号，姓名，年龄)
    const char *ct = "create table if not exists student(sn int primary key, name varchar(32), age int);";
    assert(helper.exec(ct, NULL, NULL)); // 增删改不需要返回结果

    // 3.增删改查

    // a.增
    const char *insert_sql = "insert into student values(1, 'A', 18), (2, 'B', 114514), (1919, 'C', 810);";
    assert(helper.exec(insert_sql, NULL, NULL));

    // b.删
    // const char *delete_sql = "delete from student where sn=1919";
    // assert(helper.exec(delete_sql, NULL, NULL));

    // c.改
    // const char *update_sql = "update student set name='ABC' where sn=1";
    // assert(helper.exec(update_sql, NULL, NULL));

    // d.查
    vector<vector<string>> ret;
    const char *select_sql = "select * from student";
    assert(helper.exec(select_sql, select_callback, (void *)&ret));
    for (auto &str : ret)
    {
        for (auto &s : str)
        {
            cout << s << " ";
        }
        cout << endl;
    }

    // 4.关闭数据库
    helper.close();
}